﻿using System;

using SharedGenomics.Core;
using SharedGenomics.Domain;
using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.Services;

namespace SharedGenomics.Workbench.Models
{
    public class AnalysisResultsRepository : IAnalysisResultsRepository
    {
        public AnalysisResultsRepository(IAnalysisResultsLocator resultsLocator, AnalysisResultsFileParser resultsParser, IAnalysisResultsFileReadStrategy resultsReadStrategy)
        {
            this.ResultsLocator = resultsLocator;
            this.ResultsParser = resultsParser;
            this.ResultsReadStrategy = resultsReadStrategy;
        }

        public Maybe<IAnalysisResultSet> GetResultsForJob(int jobId)
        {
            //locate stream for results file
            return this.ResultsLocator.FindResultsForJob(jobId).Bind(resultsInfo =>
            {
                using (var fs = resultsInfo.ResultsFileStream)
                {
                    var resultsFileReader = new TextDataTableReader(fs, ",");
                    return this.ResultsParser.ParseResultsFile(resultsFileReader, resultsInfo.ResultsJobType, this.ResultsReadStrategy);
                }
            });
        }

        private IAnalysisResultsLocator ResultsLocator { get; set; }
        private AnalysisResultsFileParser ResultsParser { get; set; }
        private IAnalysisResultsFileReadStrategy ResultsReadStrategy { get; set; }
    }
}
